﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.WarehouseInsp.Buz.Interfaces;
using Microhard.Core.DBUtility;
using Microhard.WarehouseInsp.Buz.DataAccess;
using Microhard.WarehouseInsp.Buz.DTO;
using Microhard.Core;
using Microhard.WarehouseInsp.Buz.Msg;
using Microhard.WarehouseInsp.Buz.Models;
using Microhard.WarehouseInsp.Buz.BuzEnum;
using System.Web.Mvc;

namespace Microhard.WarehouseInsp.Buz.Impls
{
    public class WarehouseImpl : IWarehouse
    {

        public List<WarehouseModel> GetAllWarehouse()
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            IEnumerable<Warehouse> entities = from b in db.Warehouses
                                              select b;
            if (entities.Count() > 0)
            {
                return entities.Select(m => m.ToModel()).ToList();
            }

            return new List<WarehouseModel>();
        }




        public bool IsNameDuplicate(WarehouseModel model)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            var cnt = db.Warehouses.Count(c => c.Name == model.Name);
            return cnt > 0 ? true : false;
        }

        public bool IsFileNameDuplicate(AttachmentModel model)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            var cnt = db.Attachments.Count(c => c.Name == model.Name && c.MainDataID == model.MainDataID);
            return cnt > 0 ? true : false;
        }


        public Microhard.Core.DBUtility.ExecutedResult Add(WarehouseModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();


            var op = model.ToEntity();
            if (model.EndTime.Year > model.StartTime.Year)
            {
                op.RentRange = 12 - model.StartTime.Month + model.EndTime.Month;
            }
            else
            {
                op.RentRange = model.EndTime.Month - model.StartTime.Month;
            }
            op.CreateTime = DateTime.Now;

            try
            {
                db.Warehouses.AddObject(op);
                db.SaveChanges();
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, WarehouseMsg.AddFailed);
                Log.Error("IWarehouse.Add", ex);
            }
            return rtn;
        }

        public Microhard.Core.DBUtility.ExecutedResult Update(WarehouseModel model)
        {
            ExecutedResult result = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            try
            {

                var entity = db.Warehouses.SingleOrDefault(l => l.WarehouseID == model.WarehouseID);
                if (entity != null)
                {
                    entity.WarehouseMngID = model.WarehouseMngID;
                    entity.WarehouseMngName = model.WarehouseMngName;
                    entity.Name = model.Name;
                    entity.Address = model.Address;
                    entity.Area = model.Area;
                    entity.RentRange = model.RentRange;
                    entity.WarehouseType = model.WarehouseType;
                    entity.ClacType = model.ClacType;
                    entity.CheckType = model.CheckType;
                    entity.StartTime = model.StartTime;
                    entity.EndTime = model.EndTime;
                    entity.WorkCondition = model.WorkCondition;
                    entity.LiveCondition = model.LiveCondition;
                    entity.EatCondition = model.EatCondition;
                    entity.CreateTime = DateTime.Now;

                }
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add(DBOperationFailedStatus.UpdateFailed, WarehouseMsg.UpdateFailed);
                Log.Error("IWarehouse.Update", ex);
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            var entity = db.Warehouses.Where(l => ids.Contains(l.WarehouseID));
            foreach (var e in entity)
            {

                try
                {
                    db.Warehouses.DeleteObject(e);
                    var filelist = db.Attachments.Where(n => n.MainDataID == e.WarehouseID);
                    foreach (var f in filelist)
                    {
                        db.Attachments.DeleteObject(f);
                    }
                }
                catch
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, string.Format(WarehouseMsg.NameIsInUsing, e.Name));
                }
            }
            if (result.ErrorMsg.Count == 0)
            {
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, WarehouseMsg.DeleteFailed);
                    Log.Error("IWarehouse.Delete", ex);
                }
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(WarehouseModel model)
        {
            throw new NotImplementedException();
        }

        public WarehouseModel GetModelByID(Guid id)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            var mcmp = db.Warehouses.SingleOrDefault(c => c.WarehouseID == id);
            if (mcmp != null)
            {
                return mcmp.ToModel();
            }
            return null;
        }

        public WarehouseModel GetModelByModel(WarehouseModel model)
        {
            throw new NotImplementedException();
        }

        public List<WarehouseModel> Query(WarehouseModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();

            IEnumerable<Warehouse> entities = from b in db.Warehouses
                                              select b;


            totalCount = entities.Count();
            var pagedEntities = entities.OrderByDescending(p => p.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            if (pagedEntities != null && pagedEntities.Count > 0)
            {
                return pagedEntities.Select(m => m.ToModel()).ToList();
            }

            return new List<WarehouseModel>();
        }


        public List<WarehouseModel> Query(WarehouseModel Model)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            IEnumerable<Warehouse> entities = from b in db.Warehouses
                                              select b;
            var pagedEntities = entities.OrderBy(p => p.Name).ToList();
            if (pagedEntities != null && pagedEntities.Count > 0)
                return pagedEntities.Select(m => m.ToModel()).ToList();
            return new List<WarehouseModel>();
        }

        public Microhard.Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }





        public bool IsExistByName(string name)
        {
            Guid warehouseID = Guid.Empty;
            if (Guid.TryParse(name, out warehouseID))
            {
                if (warehouseID != Guid.Empty)
                    return true;
            }
            WarehouseInspEntities db = new WarehouseInspEntities();
            var cnt = db.Warehouses.Count(w => w.Name == name);
            return cnt > 0 ? true : false;
        }
    }
}
